package com.example.mybaseapp.ui.datastore

import android.content.Context
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.lib_base.BaseActivity
import com.example.mybaseapp.R
import com.example.mybaseapp.databinding.ActivityDataStoreBinding
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking

class DataStoreActivity : BaseActivity<ActivityDataStoreBinding>() {
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "Study")
    private val key = stringPreferencesKey("name")
    private suspend fun put() = dataStore.edit { it[key] = "疫情" }
    private fun get() = runBlocking {
        return@runBlocking dataStore.data.map { it[key] ?: "新冠" }.first()
    }

    override fun onViewInit() {
        binding.btnStore.setOnClickListener {
            storeData()
        }
        binding.btnRead.setOnClickListener {
            readData()
        }
        binding.btnDel.setOnClickListener {
            delData()
        }
    }

    private fun delData() {
        runBlocking {
            dataStore.edit { it.clear() }
        }
    }

    private fun readData() {
            val data = get()
        binding.txContent.text = data
    }

    private fun storeData() {
        runBlocking {
            put()
        }
    }
}